package com.wechat.android.app.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;

import com.easemob.cases.MessageHelper;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.wechat.android.app.R;
import com.wechat.android.app.db.UserHelper;
import com.wechat.android.app.db.UserTable;
import com.wechat.android.app.global.Constants;
import com.wechat.android.app.ui.BaseActivity;
import com.wechat.android.app.ui.MainActivity;
import com.wechat.android.app.utils.ActivityHelper;
import com.wechat.android.app.utils.MyLog;
import com.wechat.android.app.utils.PhoneUtils;
import com.wechat.android.app.widget.CustomFontTextView;
import com.wechat.android.app.widget.MyEditText;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yang on 2018/1/8.
 * 登录页面
 */

public class LoginActivity extends BaseActivity {
    private static final String TAG = "LoginActivity";

    @BindView(R.id.et_mobile)
    MyEditText etMobile;
    @BindView(R.id.et_password)
    MyEditText etPassword;
    @BindView(R.id.btn_login)
    CustomFontTextView btnLogin;
    @BindView(R.id.tv_forget_password)
    CustomFontTextView tvForgetPassword;
    @BindView(R.id.tv_register)
    CustomFontTextView tvRegister;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initInjector() {
        if (getIntent().getBooleanExtra(Constants.IM_IS_SHOEW_DIALOG, false)) {
            //  PhoneUtils.ShowToastMessage(LoginActivity.this, "你的账号已在其他地方登录");

        }

    }


    @Override
    protected void initViews() {
        btnLogin.setText("\uD81B\uDF00\uD81B\uDF7A\uD81B\uDF04\uD81B\uDF7B");
        tvForgetPassword.setText("\uD81B\uDF26\uD81B\uDFC4\uD81B\uDF2F\uD81B\uDFC4\uD81B\uDFBE\uD81B\uDF50\uD81B\uDF0A\uD81B\uDFA8\uD81B\uDF08\uD81B\uDF7A");
        tvRegister.setText("\uD81B\uDF2F\uD81B\uDFBD\uD81B\uDF43\uD81B\uDFC4\uD81B\uDF0A\uD81B\uDF6A\uD81B\uDF50\uD81B\uDF37\uD81B\uDFD1\uD81B\uDF2F\uD81B\uDF51\uD81B\uDFC7");
        ActivityHelper.getInstance().keepLastActivity();
        UserTable userTable = UserHelper.getInstance().getLastLoginUser();
        if (userTable != null) {
            if (userTable.getUserAccount() != null) {
                etMobile.setText(userTable.getUserAccount());
                etMobile.setSelection(userTable.getUserAccount().length());
            }
            if (userTable.getUserPassword() != null) {
                etPassword.setText(userTable.getUserPassword());
                etPassword.setSelection(userTable.getUserPassword().length());
            }
        }


//        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
//        //拿到输入法的全部条目
//        List<InputMethodInfo> list = imm.getInputMethodList();
//        //textView中显示输入法的全部条目
//        etMobile.setText(list.toString());
//        //输入法选择框
//        imm.showInputMethodPicker();

    }

    @Override
    protected void updateViews() {

    }


    @OnClick({R.id.btn_login, R.id.tv_forget_password, R.id.tv_register})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                attemptLogin();
                break;
            case R.id.tv_forget_password:
                Intent ti = new Intent(LoginActivity.this, ForgetPasswordActivity.class);
                ti.putExtra("title", "\uD81B\uDF26\uD81B\uDFC4\uD81B\uDF2F\uD81B\uDFC4\uD81B\uDFBE\uD81B\uDF50\uD81B\uDF0A\uD81B\uDFA8\uD81B\uDF08\uD81B\uDF7A");
                startActivity(ti);
                break;
            case R.id.tv_register:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;
        }
    }

    private void attemptLogin() {
        etMobile.setError(null);
        etPassword.setError(null);
        String mobile = etMobile.getText().toString().trim();
        String password = etPassword.getText().toString();

        if (TextUtils.isEmpty(mobile)) {
            //手机号不可为空
            mMStatusDialog.show("\uD81B\uDF3A\uD81B\uDFC9\uD81B\uDF2F\uD81B\uDFA9\uD81B\uDF0A\uD81B\uDF61\uD81B\uDF26\uD81B\uDFC4\uD81B\uDF3D\uD81B\uDFA0\uD81B\uDF1E\uD81B\uDF6A\uD81B\uDF26\uD81B\uDFC4\uD81B\uDF04\uD81B\uDFD6", null);
            etMobile.requestFocus();
            return;
        }
        if (!PhoneUtils.isMobileNO(mobile)) {
            //手机号格式错误
            mMStatusDialog.show("\uD81B\uDF3A\uD81B\uDFC9\uD81B\uDF2F\uD81B\uDFA9\uD81B\uDF0A\uD81B\uDF61\uD81B\uDF3B\uD81B\uDFD8\uD81B\uDF3B\uD81B\uDF54\uD81B\uDF26\uD81B\uDFA9\uD81B\uDF3D\uD81B\uDFBE", null);
            etMobile.requestFocus();
            return;
        }


        if (TextUtils.isEmpty(password)) {
//            密码不能为空
            mMStatusDialog.show("\uD81B\uDF50\uD81B\uDF0A\uD81B\uDFA8\uD81B\uDF08\uD81B\uDF7A\uD81B\uDF26\uD81B\uDFC4\uD81B\uDF3D\uD81B\uDFA0\uD81B\uDF1E\uD81B\uDF6A\uD81B\uDF26\uD81B\uDFC4\uD81B\uDF04\uD81B\uDFD6", null);
            etPassword.requestFocus();
            return;
        }
        onLogin(mobile, password);

    }

    private void onLogin(final String mobile, final String passwd) {
        HttpParams params = new HttpParams();
        params.put("phone", mobile);
        params.put("password", passwd);
        mMProgressDialog.showNoText();
        EasyHttp.post(Constants.API_LOGIN)
                .params(params)
                .timeStamp(true)//添加时间戳
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
//                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        MyLog.e("yang", "登录失败=" + e.getMessage());
                        mMProgressDialog.dismiss();
                        mMStatusDialog.show("\uD81B\uDF1E\uD81B\uDFA9\uD81B\uDF04\uD81B\uDF7B\uD81B\uDF2F\uD81B\uDF51\uD81B\uDF62\uD81B\uDF3D\uD81B\uDF54\uD81B\uDF16\uD81B\uDF60", null);
                    }

                    @Override
                    public void onSuccess(String data) {
                        MyLog.e("yang", "登录成功==" + data);
                        String mData = PhoneUtils.checkResponseFlag(LoginActivity.this, data);
                        if (mData != null) {
                            UserHelper.getInstance().saveUserAuth(mobile, passwd, true);
                            UserHelper.getInstance().saveUserInfo(LoginActivity.this, mData);
                            UserHelper.getInstance().setIsLogined(true);
                            MessageHelper.getInstance().reset();
                            //环信服务器登陆
                            MyLog.e("yang", UserHelper.getInstance().getUserInfoModel(LoginActivity.this).getImKey() + "|" + UserHelper.getInstance().getUserInfoModel(LoginActivity.this).getPassword());
                            EMClient.getInstance().login(UserHelper.getInstance().getUserInfoModel(LoginActivity.this).getImKey(), UserHelper.getInstance().getUserInfoModel(LoginActivity.this).getPassword(), new EMCallBack() {//回调
                                @Override
                                public void onSuccess() {
                                    mMProgressDialog.dismiss();
                                    MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getName(),
                                            UserHelper.getInstance().getUserInfoModel(getApplicationContext()).getLogo());

                                    EMClient.getInstance().groupManager().loadAllGroups();
                                    EMClient.getInstance().chatManager().loadAllConversations();

                                    MyLog.e("yang", "登录聊天服务器成功！" + UserHelper.getInstance().getUserInfoModel(LoginActivity.this).getImKey() + "|" + UserHelper.getInstance().getUserInfoModel(LoginActivity.this).getPassword());
                                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                    finish();
                                }

                                @Override

                                public void onProgress(int progress, String status) {

                                }

                                @Override
                                public void onError(int code, String message) {
                                    mMProgressDialog.dismiss();
                                    MyLog.e("yang", "登录聊天服务器失败！" + code + "|" + message);
                                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                    finish();
                                }
                            });
                        } else {
                            mMProgressDialog.dismiss();
                        }
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMProgressDialog.dismiss();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }




}
